<?php

namespace app\api\service\store;

use app\api\model\store\Cart as CartModel;
use app\api\model\store\Goods as GoodsModel;
use app\api\model\store\Order as OrderModel;
use app\api\model\store\OrderAddress as OrderAddressModel;
use app\api\model\store\OrderItem as OrderItemModel;
use app\api\model\store\OrderRecord as OrderRecordModel;
use app\api\model\store\OrderComment as OrderCommentModel;
use app\api\model\user\UserAddress as UserAddressModel;
use app\api\service\user\User as UserService;
use app\api\service\store\Cart as CartService;

use think\Db;
use think\Exception;
/*use think\Log;*/

/**
 * 订单类
 */
class Order{

    protected $mCartModel = NULL;
    protected $mGoodsModel = NULL;
    protected $mOrderCommentModel = null;
    protected $sCartService = NULL;

    public function __construct(){
        $this->mCartModel = new CartModel();
        $this->mGoodsModel = new GoodsModel();

        $this->mOrderCommentModel = new OrderCommentModel();
        $this->sCartService = new CartService();
    }

    public function add($orderInfo, $userId){
        $cart_ids = $orderInfo['cart_ids'];
        //$total_price = $orderInfo['total_price'];
        $user_note = $orderInfo['user_note'];
        $addressId = $orderInfo['address_id'];
        $is_new = $orderInfo['is_new'];
        Db::startTrans();
        try{
            $cartList = $this->sCartService->lists($userId, $cart_ids, true, $is_new);
            if(!$cartList) {
                throw new Exception('购物车空，请联系管理员');
            }

            $total_num = array_sum(array_column($cartList, "num"));
            $goods_price = array_sum(array_column($cartList, "total_price"));

            $time = time();
            //新增订单
            $orderNo = build_order_no();
            $mOrderModel = new OrderModel;
            $orderData = [
                "order_no" => $orderNo,
                //"out_refund_no" => build_refund_order_no(),//退单单号
                "user_id" => $userId,
                "cart_ids" => $cart_ids,
                "total_num" => $total_num,
                "goods_price" => $goods_price,//商品费用
                "pay_price" => $goods_price,
                "total_price" => $goods_price,
                "user_note" => $user_note,
                "order_status" => 0,
                "create_time" => $time,
                "update_time" => $time
            ];
            $res = $mOrderModel->save($orderData);
            if(!$res){
                throw new Exception('新增订单失败，请联系管理员');
            }
            $orderId = $mOrderModel->id;//订单id

            $orderItemData = array_map(function($v) use($orderId, $userId){
                $v['order_id'] = $orderId;
                $v['user_id'] = $userId;
                $v['image'] = $v['origin_image'];
                unset($v['origin_image']);
                return $v;
            }, $cartList);
            $mOrderItemModel = new OrderItemModel;
            $ress = $mOrderItemModel->saveAll($orderItemData);
            if(!$ress){
                throw new Exception('新增子订单失败，请联系管理员');
            }

            $userAddress = (new UserAddressModel())->findDataByID($addressId);
            if(!$userAddress){
                throw new Exception('不存在收货地址，请联系管理员');
            }
            $orderAddressData = [
                'order_id' => $orderId,
                'user_id' => $userId,
                'name' => $userAddress['name'],
                'mobile' => $userAddress['mobile'],
                'country' => $userAddress['country'],
                'province' => $userAddress['province'],
                'city' => $userAddress['city'],
                'region' => $userAddress['region'],
                'detail' => $userAddress['detail'],
                'create_time' => $time,
                'update_time' => $time,
            ];
            $mOrderAddressModel = new OrderAddressModel;
            $resss = $mOrderAddressModel->save($orderAddressData);
            if(!$resss){
                throw new Exception('新增收货地址失败，请联系管理员');
            }
            (new OrderRecordModel())->save([
                'order_id' => $orderId,
                'type' => 'cache_add_order',
                'msg' => '订单生成',
                'create_time' => $time,
                'update_time' => $time
            ]);
            /*************************新增 order start ***************************************/
            /*************************新增订单收货地址 start ***************************************/
            /*************************订单操作表 start ***************************************/
            //更新库存

            $newGoodsList = array_map(function($v) use($orderId){
                 $v['id'] = $v['goods_id'];
                 return $v;
            }, $cartList);

            $newGoodsSkuList = array_map(function($v) use($orderId){
                $v['id'] = $v['sku_id'];
                return $v;
            }, $cartList);

            //创建订单减库存
            // goods 库存更新
            $goodsRes = (new Goods())->updateStock($newGoodsList);
            // goods_sku 库存更新
            $skuRes = (new GoodsSku())->updateStock($newGoodsSkuList);
            // 删除购物车里面的商品
            $this->sCartService->delete($userId, $cart_ids);

            Db::commit();
            return $orderId;
        }catch (Exception $e){
            //Log::record($e, 'error');
            Db::rollback();
            throwError($e->getMessage());
        }

    }


    /**
     * 根据订单id获取订单详情
     * @param $orderId
     */
    public function getDetail($orderId){
        $where['id'] = $orderId;
        return (new OrderModel())->getDetail($where);
    }

    //获取未支付的订单详情(用于订单支付)
    public function getUnpaidOrderDetail(int $orderId)
    {
        // 获取订单详情
        $orderInfo = $this->getDetail($orderId);

        // 验证订单状态
        if ($orderInfo['order_status'] != 0) {
            throwError('当前订单状态不允许支付');
        }
        // 未支付订单的过期时间
        $orderCloseTime = 2 * 60 * 60;//未支付订单 2小时自动关闭

        //1721819777
        //1721726026

        // 订单超时截止时间
        $expirationTime = strtotime($orderInfo->create_time) + $orderCloseTime;
        if ($expirationTime <= time()) {
            throwError('当前订单支付已超时，请重新下单');
        }

        // 仅返回需要的数据
        return [
            'is_payed' => false,
            'orderId' => $orderInfo['id'],
            'order_no' => $orderInfo['order_no'],
            'pay_price' => $orderInfo['pay_price'],
            'pay_status' => $orderInfo['pay_status'],
            'order_status' => $orderInfo['order_status'],
            'create_time' => $orderInfo['create_time'],
            'expirationTime' => format_time($expirationTime),
        ];
    }

    /**
     * 全部订单（包括进行中、历史订单、退款订单）  进行中订单（商家已接单） 已完成订单（就是历史订单，设定时间自动完成）
     * @param $userId
     * @param int $status ['全部','进行中','已完成'], 全部订单（包括进行中、历史订单、退款订单）  进行中订单（商家已接单） 已完成订单（就是历史订单，设定时间自动完成）
     * @param int $page
     * @param int $size
     * @return \think\response\Json
     */
    public function getList($userId = 0, $status = 0, $page = 1, $size = 15){
        $where['user_id'] = $userId;
        //'全部订单', '待付款', '待发货', '待收货','待评价','售后'
        // order_status 订单状态 0未付款 1已付款/待发货 2已发货/待收货 3已收货/待评价、已评价/已完成      -1退款/退款退货申请         -2已退款/已退款退货 -3拒绝 -4取消交易 -5关闭交易
        // pay_status 支付状态：0未支付 1已支付
        // delivery_status 发货状态(0未发货 1已发货 2部分发货)
        // receipt_status 收货状态：0未收货 1已收货
        // is_comment 未评价：0  已评价：1

        if($status == 0){ //未付款
            $where['order_status'] = 0;
            $where['pay_status'] = 0;
        }elseif($status == 1){ //待发货
            $where['order_status'] = 1;
            $where['delivery_status'] = ['in', '0,2'];
        }elseif($status == 2){ //待收货
            $where['order_status'] = 2;
            $where['delivery_status'] = 1;
            $where['receipt_status'] = 0;
        }elseif($status == 3){ //待评价
            $where['order_status'] = 3;
        }elseif($status == 4){ //待评价
            $where['order_status'] = 3;
            $where['is_comment'] = 0;
        }else{
            $where['order_status'] = ['in', '0,1,2,3'];
        }

        $orderList = (new OrderModel())->getList($where, $page, $size);
        //return $this->model->getLastSql();
        if ($orderList->isEmpty()) {
            return success('查询成功', [
                'current_page' => $orderList->currentPage(),
                'orderList' => []
            ]);
        }
        return success('查询成功', [
            'current_page' => $orderList->currentPage(),
            'orderList' => $orderList->getCollection()
        ]);
    }


    /**
     * 获取当前用户待处理的订单数量
     */
    public function getTodoCounts(){
        // 当前用户ID
        $userId = UserService::getCurrentLoginUserId();
        $mOrderModel = new OrderModel;
        return [
            'payment' => $mOrderModel->getCount($userId, 'payment'),    // 待付款的订单
            'delivery' => $mOrderModel->getCount($userId, 'delivery'),  // 待发货的订单
            'received' => $mOrderModel->getCount($userId, 'received'),  // 待收货的订单
            //'refund' => OrderRefundModel::getCountByUnderway(),  // 进行中的售后单
        ];
    }

    //用户端确认收货
    public function receipt($orderId){

        Db::startTrans();
        try{
            $time = time();
            //更新订单表
            $mOrderModel = new OrderModel;

            $data = [
                'id' => $orderId,
                'order_status' => 3,
                'receipt_status' => 1,
                'receipt_time' => $time
            ];
            $mOrderModel->saveData($data, true);

            /*************************订单操作表 start ***************************************/
            Db::name('store_order_record')->insert([
                'order_id' => $orderId,
                'type' => 'order_query_user',
                'msg' => '用户确认收货订单',
                'create_time' => $time,
                'update_time' => $time,
            ]);

            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            return false;
        }
    }

    /**
     * 取消订单
     * @param $cancelInfo
     * @return bool
     */
    public function toCancel($orderId, $reason){
        Db::startTrans();
        try{
            //更新订单表
            $time = time();
            //更新订单表
            $mOrderModel = new OrderModel;

            $data = [
                'id' => $orderId,
                'order_status' => -4,
                'refund_type' => 1,
                'refund_reason' => $reason,
                'refund_time' => $time
            ];
            $mOrderModel->saveData($data, true);

            /*************************订单操作表 start ***************************************/
            $time = time();
            Db::name('store_order_record')->insert([
                'order_id' => $orderId,
                'type' => 'order_refund',
                'msg' => '用户取消订单',
                'create_time' => $time,
                'update_time' => $time
            ]);

            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            return false;
        }
    }



    //评价订单
    public function toComment($commentInfo){

        Db::startTrans();
        try{
            $time = time();

            $this->mOrderCommentModel->saveData($commentInfo, false);
            $orderId = $commentInfo['order_id'];
            //更新订单表
            //order_status 订单状态 0未付款 1已付款/待发货 2已发货/待收货 3已收货/待评价、已评价/已完成      -1退款/退款退货申请         -2已退款/已退款退货 -3拒绝 -4取消交易 -5关闭交易
            $data[''] = 1;
            $mOrderModel = new OrderModel;
            $data = [
                'id' => $orderId,
                'is_comment' => 1,
                'comment_time' => $time
            ];
            $mOrderModel->saveData($data, true);
            //评价表新增
            /*************************订单操作表 start ***************************************/

            Db::name('store_order_record')->insert([
                'order_id' => $orderId,
                'type' => 'order_comment',
                'msg' => '用户评价',
                'create_time' => $time,
                'update_time' => $time
            ]);

            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();

            return throwError($e->getMessage());
        }
    }
















    public function getReturnOrderDetail($id){
        return $this->model->getReturnOrderInfo(['id' => $id]);
    }




    //退款或退款退货订单
    public function orderRefund($refundInfo){

        Db::startTrans();
        try{
            $order_id = $refundInfo['order_id'];
            $order = Db::name('order')->where('id', $order_id)->find();

            $refundInfo['order_type'] = $order['pay_type'];//根据订单id获取订单类型，进行回退，原路退款，订单类型：0微信退款 1余额退费
            $refundInfo['return_status'] = 1;//订单状态 0取消订单,1退款,退款退货中 3成功 4拒绝
            $this->mOrderReturnModel->saveData($refundInfo, false);

            //更新订单表
            $orderInfo['id'] = $refundInfo['order_id'];
            //order_status订单状态 0未付款,1已付款/待发货 2已发货/待收货 3已收货、待评价 4已完成 -1退款退货申请,-2已退款退货,-3拒绝,-4取消交易 -5关闭交易
            $orderInfo['order_status'] = -1;

            //return_type 0未发起售后、1取消交易、2退款 3退款退货
            $orderInfo['return_type'] = $refundInfo['return_status'];
            $this->model->saveData($orderInfo, true);

            /*************************订单操作表 start ***************************************/
            $time = time();
            //$order = Db::name('order')->where('id', $order_id)->find();
            $change_message = '用户仅退款';
            if($refundInfo['return_status'] == 3){
                $change_message = '用户退款退货';
            }
            Db::name('order_record')->insert([
                'order_id' => $order_id,
                'order_no' => $order['order_no'],
                'change_type' => 'order_return',
                'change_message' => $change_message,
                'create_time' => $time,
                'update_time' => $time,
            ]);

            $config = Db::name('config')->field('mobile')->where('id', 1)->find();
            $this->sSmsService->sendNotice($config['mobile'], 'refund');

            Db::commit();
            return true;
        }catch (Exception $e){
            Db::rollback();
            return false;
        }
    }

    public function getOrderExpress($id = 0){
        $order = $this->model->findDataByID($id);
        //dump($order['delivery_no']);die;
        $order_express = $this->mOrderExpressModel->queryData(['order_id' => $id]);
        $express = $this->mExpressSubModel->findData(['express_no' => $order['delivery_no']]);
        $order_address = $this->mOrderAddressModel->findData(['order_id' => $id]);
        //if($order && $order_express){
        /*if($order_express && $order_address){
            return [
                'order_express' => $order_express,
                'express' => $express,
                'order_address' => $order_address,
            ];
        }*/

        if($express){
            $express = json_decode($express['data'], true);
        }else{
            $express[] = [
                'context' => '打包完成，正在等待快递小哥揽收~',
                'status' => '仓库处理中',
                'time' => date('Y-m-d H:i:s', $order['delivertime'])
            ];
        }
        return [
            'order_express' => $order_express,
            'express' => $express,
            'order_address' => $order_address,
        ];
        //return false;

    }


    public function delivery($orderID, $jumpPage = ''){
        $order = OrderModel::where('id', '=', $orderID)->find();
        if (!$order) {
            throw new OrderException();
        }
        if ($order->status != OrderStatusEnum::PAID) {
            throw new OrderException([
                'msg' => '还没付款呢，想干嘛？或者你已经更新过订单了，不要再刷了',
                'errorCode' => 80002,
                'code' => 403
            ]);
        }
        $order->status = OrderStatusEnum::DELIVERED;
        $order->save();
//            ->update(['status' => OrderStatusEnum::DELIVERED]);
        $message = new DeliveryMessage();
        return $message->sendDeliveryMessage($order, $jumpPage);
    }

}